Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    pagesize: '10',
    page: 1, 
    dataList: [],
    userName: '',
    userTel: '',
    userAddress: '',
    longitude: '',
    latitude: '',
  },

  onShow() {
    this.setData({
      dataList: [],
    })
    this.getData()
  },

  // 获取数据
  getData() {
    const self = this;
    const url = "https://erp.yilestar.com/weapp/customer/pagequery"
    const data = {
      tokenId: '5d9df059c27602f5a80e2176d671f9cf',
      page: self.data.page,
      pagesize: self.data.pagesize,
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url,
      data,
      method:'post',
      success: (res) => {
        let dataList = self.data.dataList;
        const datas = res.data.data;
        dataList = dataList.concat(datas.data)
        wx.hideLoading()
        self.setData({
          dataList
        })
      }
    })
  },

  // 新增客户
  addCustomer() {
    const self = this;
    const url = "https://erp.yilestar.com/weapp/customer/add";
    const data = {
      tokenId: '5d9df059c27602f5a80e2176d671f9cf',
      CUST_NAME: self.data.userName,
      ADDR: self.data.userAddress,
      TEL: self.data.userTel,
      CONT_PRSON: self.data.userName,
      INI_FLG: 0, // 用户禁用标识
      longitude: self.data.longitude,
      latitude: self.data.latitude,
    }
    clearTimeout(self.time)
    self.time = setTimeout(() => {
      wx.request({
        url,
        data,
        method:"post",
        success: (res) => {
          wx.showLoading({
            title: '添加中'
          })
          if (res) {
            self.setData({
              active:0,
              dataList: [],
            })
            setTimeout(() => {
              wx.hideLoading()
              wx.showToast({
                title: '添加成功',
                icon: 'none',
                duration: 2000,
              })
              self.getData()
            }, 1000)
          }
        }
      })
    }, 1000)
  },

  userName(ev){
    const self = this ; 
    clearTimeout(self.time);
    self.time = setTimeout(()=>{
      self.setData({
        userName: ev.detail
      })
    },1000)
  },

  userTel(ev){
    const self = this;
    clearTimeout(self.time);
    self.time = setTimeout(() => {
      self.setData({
        userTel: ev.detail
      })
    }, 1000)
  },

  // 选择地址
  handleCheck(e) {
    wx.chooseLocation({
      complete: (cb) => {
        console.log(cb)
        this.setData({
          latitude: cb.latitude,
          longitude: cb.longitude,
          userAddress: cb.address
        })
      },
    })
  },

  // 跳转修改页面
  editMsg(e){
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../editCustomer/index?id=${id}`,
    })
    
  },

  onReachBottom(){
    var page = this.data.page;
    page++
    this.setData({
      page,
    })
    this.getData()
  },
})